#coding:utf-8

'''用户信息获取接口'''

from ihome.api_1_0 import api
from flask import request, jsonify, current_app, session, g
from ihome.utils.response_code import RET
from ihome import redis_store
from ihome.models import User
from ihome import db
from ihome.utils.login_wrapper import login_wrapper
from ihome.utils.avatar_upload import avatar_upload
from ihome.constants import UPLOAD_URL

import re

# 上传到七牛云的首行链接地址
upload_url = UPLOAD_URL


@api.route('/user_profile')
@login_wrapper
def user_profile():
    """获取用户信息,个人信息页面,返回json"""
    #todo 装饰器验证是否登陆

    try:
        user = User.query.filter_by(id=g.user_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据出错')

    # 判断用户是否存在
    if not user:
        return jsonify(errno=RET.USERERR, errmsg='用户不存在')

    # 构造返回数据
    data = {
        'user_name':user.name,
        'user_mobile':user.mobile,
        'avatar_url':upload_url+user.avatar_url
    }
    return jsonify(errno=RET.OK, errmsg='成功',data=data)


@api.route('/user_avatar', methods=['GET','POST'])
@login_wrapper
def user_avatar():
    """
    用户信息里面的个人头像设置
    post请求
    头像上传到七牛云中
    """
    # post请求过来的数据,传输到七牛云中,request通过file接收
    # get请求过来的数据,则直接返回avatar_url头像链接

    if request.method == 'GET':
        try:
            user = User.query.filter_by(id=g.user_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='查询数据出错')

        avatar_url = user.avatar_url

        # 上传成功,返回头像
        # upload_url = "http://p04b6oawq.bkt.clouddn.com/"
        url = upload_url+avatar_url
        # url = upload_url + avatar_url
        return jsonify(errno=RET.OK, errmsg='成功', data={'avatar_url': url})



    elif request.method == 'POST':

        req_obj = request.files.get('avatar')
        data = req_obj.read()
        # print(type(data))
        # print(data)
        if not data:
            return jsonify(errno=RET.PARAMERR, errmsg='无文件上传')

        # 上传头像
        #todo 这里会有延迟
        try:
            avatar_url = avatar_upload(data)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg='七牛云上传失败')

        # 保存头像链接
        try:
            User.query.filter_by(id=g.user_id).update(dict(avatar_url=avatar_url))
            db.session.commit()
        except Exception as e:

            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='查询数据出错')

        # 上传成功,返回头像
        # upload_url = "http://p04b6oawq.bkt.clouddn.com/"
        url = upload_url + avatar_url
        return jsonify(errno=RET.OK, errmsg='成功', data={'avatar_url':url})





@api.route('/user_name', methods=['GET','POST'])
@login_wrapper
def user_name():
    """
    用户信息里面的个人用户名设置
    post请求
    头像上传到七牛云中
    """
    # post请求过来的数据,传输到七牛云中,request通过file接收
    # get请求过来的数据,则直接返回avatar_url头像链接

    if request.method == 'GET':
        try:
            user = User.query.filter_by(id=g.user_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='查询数据出错')

        user_name = user.name
        return jsonify(errno=RET.OK, errmsg='成功', data={'user_name': user_name})

    elif request.method == 'POST':
        req_dict = request.get_json()
        user_name = req_dict.get('name')
        if not user_name:
            return jsonify(errno=RET.PARAMERR, errmsg='未传递用户名')

        # 保存用户名
        try:
            User.query.filter_by(id=g.user_id).update(dict(name=user_name))
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='用户名重复')

        # 修改过后需要修改session
        session['user_name'] = user_name
        return jsonify(errno=RET.OK, errmsg='成功',data={'user_name':user_name})





